package Lee_code;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

/**
 * @author blh
 * @date 2024年10月24日 9:08
 */
public class Lee_3175_1024 {
    public int findWinningPlayer(int[] skills, int k) {
        int n = skills.length;
        int maxValue = Arrays.stream(skills).max().getAsInt();
        int maxIndex = 0;
        Deque<Integer> deque = new ArrayDeque<>();
        for (int i = 0; i < skills.length; i++) {
            deque.offer(i);
            if (skills[i] == maxValue) {
                maxIndex = i;
            }
        }

        if (k >= n) {
            return maxIndex;
        }

        boolean sign = true;
        int winNum = 0;
        int cur = deque.pollFirst();
        while (sign) {
            // 选择当前的第一个元素
            while (winNum < k) {
                int temp = deque.pollFirst();
                if (skills[cur] > skills[temp]) {
                    // 胜出
                    winNum++;
                    deque.offerLast(temp);
                } else {
                    // 输麻了
                    winNum = 1;
                    deque.offerLast(cur);
                    cur = temp;
                }
            }
            if (winNum == k) {
                return cur;
            }
        }
        return cur;
    }
}
